<?php
namespace app\behavior;
use think\Controller;

class CheckPermission extends Controller{

  //免验证控制器
  private $notCheckController = [
    'Admin.index',
  ];

  //免验证方法
  private $notCheckFunction = [
    'Admin.trumpet.line2'
  ];

  public function checkPermission(){
    $current_controller = request()->controller();
    $current_function = request()->controller().'.'.request()->action();
    $current_url = '/'.strtolower(str_replace('.','/',$current_function));
    //获取json菜单数组
    $json_file = file_get_contents('static/json/sidemenu.json');
    $sideMenu = json_decode($json_file,true);
    $tmpArr = [];
    foreach($sideMenu as $value){
      if($value['href'] == 'javascript:;'){
        foreach($value['menu'] as $val){
          $tmpArr[$val['href']] = $val['permission'];
        }
      }else{
        $tmpArr[$value['href']] = $value['permission'];
      }
    }
    //end
    //如果json菜单不存在该url,排除admin/index/index和超级超级管理员
    if($current_url != '/admin/index/index' && session('userInfo.role_id') != 0){
      if(isset($tmpArr[$current_url])){
        //如果json菜单不存在该url
        if(!in_array($current_controller,$this->notCheckController)
          && !in_array($current_function,$this->notCheckFunction)){
          //验证start
          $check = false;
          if(session('userInfo.role_id') == 0){
            $check = true;
          }else{
            $userPermission = session('?userInfo.permission') ? session('userInfo.permission') : '';
            if(!empty($userPermission)){
              foreach ($userPermission as $key=>$value){
                if($value == $tmpArr[$current_url]){
                  $check = true;
                }
              }
            }
          }
          //验证end
          if($check == false){
            $this->redirect('/admin/index');
          }
        }
      }else{
        //未知url
        $this->redirect('/admin/index');
      }
    }
  }


}//END